//
//  AppAuthManager.m
//  YYDemo
//
//  Created by lipeng on 2019/4/20.
//  Copyright © 2019 lipeng. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>
#import <UIKit/UIKit.h>
#import "AppAuthManager.h"

@implementation AppAuthManager
IMSingletonM(AppAuthManager)



- (BOOL)checkCameraPermissions {
    BOOL isAccess = NO;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        isAccess = YES;
    }
    else {
        [self showApplicationSetting];
    }
    return isAccess;
}


- (BOOL)checkPhotoLibraryPermissions {
    BOOL isAccess = NO;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        isAccess = YES;
    }
    else {
        [self showApplicationSetting];
    }
    return isAccess;
}

// location

- (BOOL)startUpByLocationManager:(CLLocationManager *)locationManager {
    NSAssert(locationManager != nil, @"缺少地理位置管理");
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            // 用户还未选择，一般初次使用时为该状态
            if ([CLLocationManager locationServicesEnabled]) {
                 [locationManager requestWhenInUseAuthorization];
            }
            else {
                // alert 服务过去处理
                NSLog(@"=== 地理位置服务不可用 ===");
                [self showApplicationSetting];
                return NO;
            }
            break;
        case kCLAuthorizationStatusDenied:
        {
            // 用户拒绝使用位置服务
            [self showApplicationSetting];
        }
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            // 用户仅同意在应用使用期间使用位置服务
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            // 用户同意一直使用位置服务，前台/后台
            break;
        case kCLAuthorizationStatusRestricted:
            // 位置服务受限
            break;
        default:
            break;
    }
    return YES;
}


#pragma mark - 访问受限下,跳转到系统设置

- (void)showApplicationSetting {
    // 跳转到设置,打开权限开关
    // [[UIApplication sharedApplication] openURL:url]; 报错:
    //  使用UIAlertController 跳转到系统设置的时候出现如下bug或警告:
    // _BSMachError: port 7113; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"
    // _BSMachError: port 7113; (os/kern) invalid name (0xf) "Unable to deallocate send right"
    // 解决方式 : 多线程延迟调用解决这个问题
    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    dispatch_after(0.2, dispatch_get_main_queue(), ^{
        [App openURL:url];
    });
}


@end
